
package com.common.event;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.annotation.PreDestroy;


/**
 * 
* @Title: ExecutorManager.java 
* @Package com.common.event
* @Description: 线程池管理器
* @author tangzhibin
* @date 2016年10月12日 
* @version V1.0
 */
public class ExecutorManager {
	
	ExecutorService pool=null;
	
	public ExecutorManager(){
		pool = Executors.newFixedThreadPool(getPoolSize());
	}
	
	public ExecutorManager(int poolSize){
		pool = Executors.newFixedThreadPool(poolSize);
	}
	
	
	
	public static int getPoolSize() {
		double coefficient = 0.8; // CPU密集型接近0，IO密集型接近1
		int numberOfCores = Runtime.getRuntime().availableProcessors();
		int poolSize = (int) (numberOfCores / (1 - coefficient));
		return poolSize;
	}

	public <T> void addTask(Callable<T> task) throws Exception{
		this.addTask(task, false);
	}
	
	public <T> void addTask(Callable<T> task,boolean sync) throws Exception {
		Future<T> f = pool.submit(task);
		if(sync)	f.get();
		return;
	}
	
	
	public ExecutorService getPool() {
		return pool;
	}

	@PreDestroy
	public void shutdown(){
		if(this.pool!=null && !this.pool.isShutdown()){
			this.pool.shutdown();
		}
	}
	
	
	
	

}
